<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Phone, Search } from '@element-plus/icons-vue';
import { el, pa } from 'element-plus/es/locale';
import http from '@/http';

// 创建一个表单实例的引用，用于后续操作表单
const formRef = ref<FormInstance>();
const IDNumber = ref('');

// 自定义姓名验证函数
const validateName = (rule: any, value: string, callback: any) => {
  // 姓名的验证规则：仅允许中文或英文字符
  if (value === '') {
    callback(new Error('请输入患者姓名'));
  } else if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(value)) {
    callback(new Error('请输入正确的患者姓名，仅允许中文或英文字符'));
  } else {
    callback();
  }
};

// 自定义电话验证函数
const validatePhone = (rule: any, value: string, callback: any) => {
  // 电话号码的正则表达式，以1开头，第二位为3-9之间的数字，后面跟9位数字
  const phoneReg = /^1[3-9]\d{9}$/;
  if (value === '') {
    callback(new Error('请输入患者电话'));
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的患者电话'));
  } else {
    callback();
  }
};

// 自定义年龄验证函数
const validateAge = (rule: any, value: string, callback: any) => {
  // 年龄的验证规则：正整数
  const ageReg = /^[1-9]\d*$/;
  if (value === '') {
    callback(new Error('请输入患者年龄'));
  } else if (!ageReg.test(value)) {
    callback(new Error('请输入正确的患者年龄，应为正整数'));
  } else {
    callback();
  }
};

// 重置表单的函数
const resetForm = (formEl: FormInstance | undefined) => {
  // 如果表单实例不存在，直接返回
  if (!formEl) return;
  // 调用表单实例的 resetFields 方法重置表单字段
  formEl.resetFields();
};

//出身日期
const value1 = ref('')


let flag = ref(false)

//病人信息
const patient = ref({
  patientId: '',
  idCard: '',
  patientName: '',
  phone: '',
  sex: '',
  age: '',
  birthday: '',
  address: '',
  deptId: '',
  schedulingType: '',
  subsectionType: '',
  createTime: ''
});
// 自定义身份证号码验证函数
const validateIDNumber = (rule: any, value: string, callback: any) => {
  patient.value = {
    patientId: '',
    idCard: '',
    patientName: '',
    phone: '',
    sex: '',
    age: '',
    birthday: '',
    address: '',
    deptId: '',
    schedulingType: '',
    subsectionType: '',
    createTime: ''
  }
  value = IDNumber.value;
  // 简单的18位身份证号码正则表达式校验示例，实际可能需要更复杂严谨的校验
  const idNumberReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (value == '') {
    callback(new Error('请输入身份证号'));
  } else if (!idNumberReg.test(value)) {
    callback(new Error('请输入正确的身份证号码'));
  } else {
    http.get('/hisPatient/getIdCardAll?idCard=' + value)
      .then((res) => {
        if (res != "") {
          ElMessage({
            message: '请确认你的信息！',
            type: 'success',
          })
          patient.value = res;
          flag.value = true

          console.log(flag.value);
        } else {
          ElMessage({
            message: '请输入你的详细信息！',
            type: 'warning',
          })
          flag.value = false;
        }
      })
  }
};


// 挂号类型
const RegistrationType = ref('门诊');

const options = [
  '门诊',
  '门诊+病例本',
  '急诊',
  '急诊+病例本',
  '孕诊',
  '孕诊+病例本'
];

// 挂号费用
const registrationFee = ref(20);


//挂号收费
function submitRegistrationFee() {
  // 验证patient对象中的关键属性是否为空
  if (!patient.value.patientName) {
    ElMessage({
      message: '患者姓名不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.phone) {
    ElMessage({
      message: '患者电话不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.idCard) {
    ElMessage({
      message: '患者身份证号不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.sex) {
    ElMessage({
      message: '患者性别不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.age) {
    ElMessage({
      message: '患者年龄不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.birthday) {
    ElMessage({
      message: '患者生日不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.address) {
    ElMessage({
      message: '患者地址不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.deptId) {
    ElMessage({
      message: '患者所属科室不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.schedulingType) {
    ElMessage({
      message: '挂号类型不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.subsectionType) {
    ElMessage({
      message: '挂号时间段不能为空',
      type: 'error'
    });
    return;
  }
  if (!patient.value.createTime) {
    ElMessage({
      message: '挂号时间不能为空',
      type: 'error'
    });
    return;
  }
  //查询患者是否存在，如果不存在，先添加患者信息，再添加挂号信息

  // 添加新的患者信息
  if (flag.value) {
    http.post('/hisRegistration/addHisRegistration', patient.value)
      .then((res) => {
        if (res == 1) {
          ElMessage({
            message: '挂号成功',
            type: 'success',
          })
          getQueryDepartmentRegistrationInformation()
        }
      })
  } else {
    http.post('/hisPatient/addHisPatient', patient.value)
      .then((res) => {
        if (res != '') {
          ElMessage({
            message: '已保存您的信息',
            type: 'success',
          })
          patient.value.patientId = res;

          http.post('/hisRegistration/addHisRegistration', patient.value)
            .then((res) => {
              if (res == 1) {
                ElMessage({
                  message: '挂号成功',
                  type: 'success',
                })
                getQueryDepartmentRegistrationInformation()
              }
            })
        }
      })


  }

}

function Fee() {
  if (RegistrationType.value === '门诊') {
    registrationFee.value = 20;
  } else if (RegistrationType.value === '门诊+病例本') {
    registrationFee.value = 30;
  } else if (RegistrationType.value === '急诊') {
    registrationFee.value = 25;
  } else if (RegistrationType.value === '急诊+病例本') {
    registrationFee.value = 35;
  } else if (RegistrationType.value === '孕诊') {
    registrationFee.value = 10;
  } else if (RegistrationType.value === '孕诊+病例本') {
    registrationFee.value = 15;
  }
}

//科室挂号信息
const departmentTableData = ref([])
onMounted(() => {
  //调用获取当前页相关用户数据的方法
  getQueryDepartmentRegistrationInformation()
})
//查询科室挂号信息
function getQueryDepartmentRegistrationInformation() {
  http.get('/department/selectRegistrationList')
    .then((res) => {
      departmentTableData.value = res;
    })
}
</script>

<template>
  <!-- 加载患者信息 -->
  <el-form ref="formRef" style="max-width: 600px" label-width="auto" class="demo-ruleForm"
    hide-required-asterisk="false">
    <el-row>
      <el-col :span="16">
        <el-form-item label="身份证号" prop="IDNumber" :rules="[
          { validator: validateIDNumber, trigger: 'blur' }
        ]">
          <el-input v-model="IDNumber" placeholder="请输入患者身份证号" type="text" autocomplete="off" />
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      <el-col :span="8">
        <el-form-item>
          <!-- 点击提交按钮时调用submitForm方法 -->
          <el-button style="margin-left: 200px;" type="primary"><el-icon>
              <Search />
            </el-icon>&nbsp;加载患者信息</el-button>
        </el-form-item>
        <div class="grid-content ep-bg-purple-light"></div>
      </el-col>
    </el-row>

  </el-form>


  <!-- 患者信息 -->
  <el-form style="max-width:" :model="patient" label-width="auto" class="demo-ruleForm">
    <el-row>


      <el-col :span="6">
        <el-form-item label="身份证号">
          <!-- 输入框绑定sfz的sfz属性，类型为文本，自动补全关闭 -->
          <el-input v-model="patient.idCard" type="text" autocomplete="off" placeholder="患者身份证号" />
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      <el-col :span="6">
        <el-form-item label="患者姓名" prop="name" :rules="[
          { validator: validateName, trigger: 'blur' }
        ]">
          <!-- 输入框绑定 numberValidateForm 的 name 属性，类型为文本，自动补全关闭 -->
          <el-input v-model="numberValidateForm.name" type="text" autocomplete="off" />
          <el-input v-model="patient.patientName" type="text" autocomplete="off" placeholder="患者姓名" property="name" />
          <el-input v-model="patient.patientName" type="text" autocomplete="off" placeholder="患者姓名" property="name" />
        </el-form-item>
        <div class="grid-content ep-bg-purple-light"></div>
      </el-col>
      <el-col :span="6">
        <el-form-item label="患者电话" prop="phone" :rules="[
          { validator: validatePhone, trigger: 'blur' }
        ]">
          <!-- 输入框绑定 numberValidateForm 的 phone 属性，类型为文本，自动补全关闭，占位符为出生日期 -->
          <el-input v-model="numberValidateForm.phone" type="text" autocomplete="off" placeholder="出生日期" />

          <!-- 输入框绑定phone属性，类型为文本，自动补全关闭，占位符为出生日期 -->
          <el-input v-model="patient.phone" type="text" autocomplete="off" placeholder="患者电话" property="phone" />
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="性别">
          <div id="app">
            <input type="radio" id="male" value="0" v-model="patient.sex" :checked="patient.sex === '0'">
            <label for="male">男</label>
            <input type="radio" id="female" value="1" v-model="patient.sex" :checked="patient.sex === '1'">
            <label for="female">女</label>
            <input type="radio" id="unknown" value="2" v-model="patient.sex" :checked="patient.sex === '2'">
            <label for="unknown">未知</label>
          </div>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content ep-bg-purple-light"></div>
        <el-form-item label="出生日期" prop="dateOfBirth">
          <div class="block">
            <el-date-picker v-model="patient.birthday" type="date" placeholder="出生日期"
              :default-value="new Date(2024, 1, 1)" />
          </div>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="患者年龄" prop="age" :rules="[
          { validator: validateAge, trigger: 'blur' }
        ]">
          <!-- 输入框绑定age属性，类型为文本，自动补全关闭 -->
          <el-input v-model="patient.age" type="text" autocomplete="off" placeholder="患者年龄" property="age" />
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="地址信息">
          <el-input v-model="patient.address" type="text" autocomplete="off" placeholder="地址信息" property="address" />
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
    </el-row>
    <div>
      <el-segmented v-model="RegistrationType" :options="options" @change="Fee" />
      <div style="float: right; margin-right: 200px;">
        <span>挂号费用：{{ registrationFee }}</span>
        <el-button style="margin-left: 10px;background-color: red;" type="primary" @click="submitRegistrationFee">
          <el-icon>
            <Search />
          </el-icon>挂号收费
        </el-button>
      </div>
    </div>
    <br>

    <el-row type="flex" justify="" :model="patient">
      <el-col :span="6">
        <el-form-item label="所属科室">
          <!-- 输入框绑定age属性，类型为文本，自动补全关闭 -->
          <el-select v-model="patient.deptId" placeholder="请选择所属科室" clearable>
            <el-option label="内科" value="101" />
            <el-option label="外科" value="102" />
            <el-option label="儿科" value="103" />
            <el-option label="妇科" value="104" />
            <el-option label="眼科" value="105" />
            <el-option label="耳鼻喉科" value="106" />
            <el-option label="口腔科" value="107" />
            <el-option label="皮肤科" value="108" />
            <el-option label="其他" value="109" />
          </el-select>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="挂号类型">
          <!-- 输入框绑定age属性，类型为文本，自动补全关闭 -->
          <el-select v-model="patient.schedulingType" placeholder="请选择挂号类型" clearable>
            <el-option label="门诊" value="1" />
            <el-option label="门诊+病例本" value="2" />
            <el-option label="急诊" value="3" />
            <el-option label="急诊+病例本" value="4" />
            <el-option label="孕诊" value="5" />
            <el-option label="孕诊+病例本" value="6" />
          </el-select>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="挂号时间段">
          <!-- 输入框绑定age属性，类型为文本，自动补全关闭 -->
          <el-select v-model="patient.subsectionType" placeholder="请选择挂号时间段" clearable>
            <el-option label="上午" value="1" />
            <el-option label="下午" value="2" />
            <el-option label="晚上" value="3" />
          </el-select>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>

      <el-col :span="6">
        <el-form-item label="挂号时间" prop="registrationTime">
          <div class="block">
            <el-date-picker v-model="patient.createTime" type="date" placeholder="请选择挂号时间" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" :default-value="new Date(2024, 1, 1)" />
          </div>
        </el-form-item>
        <div class="grid-content ep-bg-purple"></div>
      </el-col>
    </el-row>
  </el-form>

  <el-table :data="departmentTableData" border style="width: 100%">
    <el-table-column property="deptId" label="科室ID" />
    <el-table-column property="deptName" label="科室名称" />
    <el-table-column property="currentNumber" label="当前号数" />
  </el-table>
</template>

<style scoped></style>
